//
//  SouCangViewController.m
//  KeepFit
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 Fuzzie Liu. All rights reserved.
//

#import "SouCangViewController.h"
#import "ResultTableViewCell.h"
#import "FoodDetail.h"
#import "FinalViewController.h"
#import <MBProgressHUD.h>
@interface SouCangViewController ()<UITableViewDataSource,UITableViewDelegate, UISearchBarDelegate, MBProgressHUDDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *souSuoTableView;
@property (nonatomic, strong) NSMutableArray *bigArr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSNumber *total_pages;
@end

@implementation SouCangViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor redColor];
//    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back.jpg"]];
    
    
    
    UIImageView *backView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    backView.image = [UIImage imageNamed:@"beijingtu.jpeg"];
    UIBlurEffect *blueEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blueEffect];
    effectView.frame = self.view.bounds;
    [backView addSubview:effectView];

    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(fanHui:)];
    self.bigArr = [NSMutableArray array];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonAction:)];
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100, 0)];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"想吃些什么呢";
    self.navigationItem.titleView = self.searchBar;
    
    self.souSuoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.souSuoTableView.delegate = self;
    self.souSuoTableView.dataSource = self;
    self.souSuoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.souSuoTableView];
    
    [self.souSuoTableView registerClass:[ResultTableViewCell class] forCellReuseIdentifier:@"RESULT"];
    
    self.souSuoTableView.footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(freshData)];
    self.souSuoTableView.backgroundView = backView;
    
}
- (void)freshData
{
    if (self.page == [self.total_pages integerValue]) {
        self.souSuoTableView.footer.state = MJRefreshStateNoMoreData;
        self.page = [self.total_pages integerValue];
    }else
    {
        self.page++;
        [self searchHandle];
        [self.souSuoTableView.footer endRefreshing];
    }
    
    
}



- (void)rightBarButtonAction:(UIBarButtonItem *)item
{
    [self.searchBar resignFirstResponder];
   
}
- (void)fanHui:(UIBarButtonItem *)item
{
    [self.searchBar resignFirstResponder];
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.bigArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ResultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RESULT"];
    FoodDetail *food = [self.bigArr objectAtIndex:indexPath.row];
    
    [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:food.thumb_image_url] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    cell.nameLabel.text = food.name;
    switch ([food.health_light intValue])
    {
        case 1:
            cell.typeImageView.image = [UIImage imageNamed:@"qing.png"];
            break;
        case 2:
            cell.typeImageView.image = [UIImage imageNamed:@"jiaozhong.png"];
            break;
        case 3:
            cell.typeImageView.image = [UIImage imageNamed:@"zhong.png"];
            break;
            
        default:
            break;
    }
    
#pragma mark  高亮 ------
    NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:food.name];
    
    // 获取标红的位置和长度
    NSRange range = [food.name rangeOfString:self.searchBar.text];
    
    // 设置标签文字的属性
    [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:235 / 255.0 green:77/ 255.0 blue:66 / 255.0 alpha:1.0], NSFontAttributeName : [UIFont boldSystemFontOfSize:22]} range:range];
    
    // 显示在Label上
    cell.nameLabel.attributedText = attrituteString;
    if (food.is_liquid == YES) {
        
        cell.energyLabel.text = [NSString stringWithFormat:@"%@千焦/100克",food.calory];
    }else
    {
        cell.energyLabel.text = [NSString stringWithFormat:@"%@大卡/100克",food.calory];
    }
    cell.energyLabel.textColor = [UIColor redColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.page = 1;
    [self.bigArr removeAllObjects];
    [self searchHandle];
    [self.searchBar resignFirstResponder];
}

- (void)searchHandle
{
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.color = [UIColor colorWithRed:0.13 green:0.10 blue:0.10 alpha:0.9];
    hub.removeFromSuperViewOnHide = YES;
    
    hub.delegate = self;
    hub.labelText = @"玩命加载中...";
    NSString *str = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods/search?q=%@&page=%ld",self.searchBar.text,self.page];
    // 转码 不转不出来
    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    [NetWorkingCache getUrl:str success:^(id result) {
        self.total_pages = [result objectForKey:@"total_pages"];
        NSArray *arr = [result objectForKey:@"foods"];
        for (NSDictionary *dic in arr) {
            FoodDetail *food = [FoodDetail modelWithDic:dic];
            [self.bigArr addObject:food];
        }
        NSLog(@"------------%ld",self.bigArr.count);
        if (self.bigArr.count == 0) {
            UIAlertController *alentController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您输入的不正确" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
            [alentController addAction:action];
            [self presentViewController:alentController animated:YES completion:nil];
        }

        [self.souSuoTableView reloadData];
        [hub hide:YES];
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
        
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoodDetail *food = [self.bigArr objectAtIndex:indexPath.row];
    FinalViewController *finalVC = [[FinalViewController alloc] init];
    finalVC.foodCode = food.code;
    [self.navigationController pushViewController:finalVC animated:YES];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
